import { useEffect, useState } from "react";

type Props = {
  open: boolean;
  onClose: () => void;
};

const STORAGE_PROVIDER_KEY = "ai_agent_llm_provider"; // 'openai' | 'ollama'
const STORAGE_OPENAI_KEY = "ai_agent_openai_key";

export function SettingsModal({ open, onClose }: Props) {
  const [provider, setProvider] = useState<string>(() => {
    try {
      return localStorage.getItem(STORAGE_PROVIDER_KEY) || "ollama";
    } catch {
      return "ollama";
    }
  });
  const [openaiKey, setOpenaiKey] = useState<string>(() => {
    try {
      return localStorage.getItem(STORAGE_OPENAI_KEY) || "";
    } catch {
      return "";
    }
  });
  const [showKey, setShowKey] = useState(false);

  useEffect(() => {
    if (!open) return;
    // refresh from storage when opened (in case changed elsewhere)
    try {
      const p = localStorage.getItem(STORAGE_PROVIDER_KEY);
      const k = localStorage.getItem(STORAGE_OPENAI_KEY);
      if (p) setProvider(p);
      if (k) setOpenaiKey(k);
    } catch {
      // noop
    }
  }, [open]);

  if (!open) return null;

  const handleSave = () => {
    try {
      localStorage.setItem(STORAGE_PROVIDER_KEY, provider);
      localStorage.setItem(STORAGE_OPENAI_KEY, openaiKey);
    } catch (e) {
      console.error("Failed to save settings", e);
    }
    onClose();
  };

  const handleCancel = () => {
    // reset local state to stored values
    try {
      const p = localStorage.getItem(STORAGE_PROVIDER_KEY) || "ollama";
      const k = localStorage.getItem(STORAGE_OPENAI_KEY) || "";
      setProvider(p);
      setOpenaiKey(k);
    } catch {
      // noop
    }
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/50" onClick={handleCancel} />
      <div className="relative bg-white rounded-lg shadow-lg w-full max-w-lg mx-4 p-6">
        <div className="flex items-start justify-between">
          <h2 className="text-lg font-semibold">设置</h2>
          <button className="text-sm text-gray-500" onClick={handleCancel}>
            关闭
          </button>
        </div>

        <div className="mt-4 text-sm text-gray-700 space-y-4">
          <div>
            <label className="block font-medium mb-2">LLM 提供者</label>
            <div className="flex gap-4">
              <label className="inline-flex items-center gap-2">
                <input
                  type="radio"
                  name="provider"
                  value="ollama"
                  checked={provider === "ollama"}
                  onChange={() => setProvider("ollama")}
                />
                本地 Ollama
              </label>

              <label className="inline-flex items-center gap-2">
                <input
                  type="radio"
                  name="provider"
                  value="openai"
                  checked={provider === "openai"}
                  onChange={() => setProvider("openai")}
                />
                OpenAI API
              </label>
            </div>
          </div>

          {provider === "openai" && (
            <div>
              <label className="block font-medium mb-2">OpenAI API Key</label>
              <div className="flex items-center gap-2">
                <input
                  type={showKey ? "text" : "password"}
                  value={openaiKey}
                  onChange={(e) => setOpenaiKey(e.target.value)}
                  placeholder="sk-..."
                  className="block w-full px-3 py-2 border border-gray-300 rounded"
                />
                <button
                  onClick={() => setShowKey((s) => !s)}
                  className="text-sm text-gray-600 px-2 py-1 border rounded"
                >
                  {showKey ? "隐藏" : "显示"}
                </button>
              </div>
              <p className="text-xs text-gray-500 mt-1">此 API Key 会保存在浏览器的 localStorage 中，仅用于本地开发测试。</p>
            </div>
          )}

          <div className="flex justify-end gap-2 pt-2">
            <button className={"px-3 py-1 rounded border text-sm"} onClick={handleCancel}>取消</button>
            <button className={"px-3 py-1 rounded bg-blue-600 text-white text-sm"} onClick={handleSave}>保存</button>
          </div>
        </div>
      </div>
    </div>
  );
}
